package com.ls.blog.config;


import com.ls.blog.common.enums.ResultCode;
import com.ls.blog.common.exception.BizException;
import com.ls.blog.utils.R;
import com.ls.blog.utils.Result;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
public class ControllerAdviceHandler {

    /**
     * 处理业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public Result<?> errorHandler(BizException e) {
        return R.fail(e.getMessage());
    }


    /**
     * 校验错误异常
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> handerValidException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        HashMap<Object, Object> map = new HashMap<>();
        result.getFieldErrors().forEach((fieldError -> {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }));
        return R.fail(ResultCode.PARAM_ERROT,map);
    }

    /**
     * 处理系统
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result<?> errorHandler(Exception e) {
        e.printStackTrace();
        return R.fail(ResultCode.SYS_ERROR);
    }
}
